package com.sap.sap_mangers.service.Impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sap.sap_mangers.mapper.ActivityMapper;
import com.sap.sap_mangers.mapper.UserMapper;
import com.sap.sap_mangers.pojo.User;
import com.sap.sap_mangers.service.CacheService;
import com.sap.sap_mangers.until.ConstantUntil;
import com.sap.sap_mangers.until.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * 缓存服务impl
 * 各个数据缓存的service层
 *
 * @author 樊东升
 * @date 2022/8/12 11:58
 */
@Service
public class CacheServiceImpl implements CacheService {

    /**
     * 复述,缓存
     */
    @Autowired
    private RedisCache redisCache;
    /**
     * 用户映射器
     */
    @Autowired
    private UserMapper userMapper;
    /**
     * 活动映射器
     */
    @Autowired
    private ActivityMapper activityMapper;


    /**
     * 得到真实姓名缓存
     *
     * @param cache    缓存
     * @param username 用户名
     * @return {@link String}
     */
    @Override
    public String getRealNameCache(Map<String, String> cache, String username) {
        String realName = cache.get(username);
        if (realName != null) {
            return realName;
        }
        return updateUserMessage(userMapper.getRealNameByUserName(username), cache, username, redisCache, ConstantUntil.CACHE_USER_REAL_NAME, getRealNameCacheMap());
    }

    /**
     * 得到真实姓名缓存地图
     *
     * @return {@link Map}<{@link String}, {@link String}>
     */
    @Override
    public Map<String, String> getRealNameCacheMap() {
        return redisCache.getCacheMap(ConstantUntil.CACHE_USER_REAL_NAME);
    }

    /**
     * 获得头缓存
     *
     * @param cache    缓存
     * @param username 用户名
     * @return {@link String}
     */
    @Override
    public String getHeaderCache(Map<String, String> cache, String username) {
        String headerUrl = cache.get(username);
        if (headerUrl != null) {
            return headerUrl;
        }
        return updateUserMessage(userMapper.getUserHeadShot(username), cache, username, redisCache, ConstantUntil.CACHE_USER_HEADER, getHeaderCacheMap());
    }

    @Override
    public String updateUserHeaderUrl(Map<String, String> cache, String username) {
        return updateUserMessage(userMapper.getUserHeadShot(username), cache, username, redisCache, ConstantUntil.CACHE_USER_HEADER, getHeaderCacheMap());
    }

    private String updateUserMessage(String userMapper, Map<String, String> cache, String username, RedisCache redisCache, String cacheUserHeader, Map<String, String> HeaderCacheMap) {
        cache.put(username, userMapper);
        redisCache.setCacheMap(cacheUserHeader, cache);
        cache.clear();
        cache.putAll(HeaderCacheMap);
        return userMapper;
    }

    /**
     * 获得头缓存地图
     *
     * @return {@link Map}<{@link String}, {@link String}>
     */
    @Override
    public Map<String, String> getHeaderCacheMap() {
        return redisCache.getCacheMap(ConstantUntil.CACHE_USER_HEADER);
    }

    /**
     * 获取用户
     *
     * @return {@link Map}<{@link String}, {@link String}>
     */
    @Override
    public Map<String, String> getUser() {
        return redisCache.getCacheMap(ConstantUntil.CACHE_USER);
    }

    /**
     * 更新用户
     *
     * @param username 用户名
     */
    @Override
    public void updateUser(String username) {
        Map<String, Object> cacheMap = redisCache.getCacheMap(ConstantUntil.CACHE_USER);
        User userByUserName = userMapper.getUserByUserName(username);
        String jsonUser = JSON.toJSONString(userByUserName);
        cacheMap.put(username, jsonUser);
        redisCache.setCacheMap(ConstantUntil.CACHE_USER, cacheMap);
    }

    /**
     * 得到活动图像
     *
     * @param uuid uuid
     * @return {@link List}<{@link String}>
     */
    @Override
    public List<String> getActivityImage(String uuid) {
        Map<String, Object> cacheMap = redisCache.getCacheMap(ConstantUntil.CACHE_ACTIVITY_IMAGES);
        try {
            String jsonObject = (String) cacheMap.get(uuid);
            if (jsonObject == null) {
                List<String> imageById = activityMapper.getImageById(Long.valueOf(uuid));
                String jsonString = JSON.toJSONString(imageById);
                cacheMap.put(uuid, jsonString);
                redisCache.setCacheMap(ConstantUntil.CACHE_ACTIVITY_IMAGES, cacheMap);
                return imageById;
            }
            return JSONObject.parseArray(jsonObject, String.class);
        } catch (ClassCastException e) {
            return null;
        }
    }

    /**
     * 更新活动图像
     *
     * @param images 图片
     * @param oldId  老id
     * @param newId  新id
     */
    @Override
    public void updateActivityImage(List<String> images, String oldId, String newId) {
        Map<String, Object> cacheMap = redisCache.getCacheMap(ConstantUntil.CACHE_ACTIVITY_IMAGES);
        String jsonString = JSON.toJSONString(images);
        cacheMap.put(newId, jsonString);
        cacheMap.remove(oldId);
        redisCache.deleteObject(ConstantUntil.CACHE_ACTIVITY_IMAGES);
        redisCache.setCacheMap(ConstantUntil.CACHE_ACTIVITY_IMAGES, cacheMap);
    }

    @Override
    public void setPasswordCode(String code, String username) {
        Map<String, Object> cacheMap = redisCache.getCacheMap(ConstantUntil.CACHE_USER_PASSWORD_CODE);
        cacheMap.put(username, code);
        redisCache.deleteObject(ConstantUntil.CACHE_USER_PASSWORD_CODE);
        redisCache.setCacheMap(ConstantUntil.CACHE_USER_PASSWORD_CODE, cacheMap);
    }

    @Override
    public String getPasswordCode(String username) {
        Map<String, Object> cacheMap = redisCache.getCacheMap(ConstantUntil.CACHE_USER_PASSWORD_CODE);
        if (cacheMap.containsKey(username)) {
            String passwordCode = (String) cacheMap.get(username);
            cacheMap.remove(username);
            redisCache.deleteObject(ConstantUntil.CACHE_USER_PASSWORD_CODE);
            redisCache.setCacheMap(ConstantUntil.CACHE_USER_PASSWORD_CODE, cacheMap);
            return passwordCode;
        }
        return null;
    }

    @Override
    public void updateSapIfOpenJoinFunction() {
        if (getSapIfOpenJoinFunction()) {
            //如果原本是开启状态就将其关闭
            redisCache.setCacheObject(ConstantUntil.SAP_IF_OPEN_JOIN_FUNCTION, "0");
        } else {
            //否则开启
            redisCache.setCacheObject(ConstantUntil.SAP_IF_OPEN_JOIN_FUNCTION, "1");
        }
    }

    @Override
    public boolean getSapIfOpenJoinFunction() {
        Object ifOpenJoinFunction = redisCache.getCacheObject(ConstantUntil.SAP_IF_OPEN_JOIN_FUNCTION);
        //如果redis中没找到是否开启接口标识或标识的值不为"0"或"1" -> 将标识设置为"0"并返回false(不开启)
        //否则返回获取到的值对应的bool ("0"->返回false标识不开启，"1"->返回true标识开启)
        if (ifOpenJoinFunction == null) {
            redisCache.setCacheObject(ConstantUntil.SAP_IF_OPEN_JOIN_FUNCTION, "0");
            return false;
        } else if ("0".equals(ifOpenJoinFunction)) {
            return false;
        } else if ("1".equals(ifOpenJoinFunction)) {
            return true;
        } else {
            redisCache.setCacheObject(ConstantUntil.SAP_IF_OPEN_JOIN_FUNCTION, "0");
            return false;
        }
    }

    @Override
    public void closeSapIfOpenJoinFunction() {
        redisCache.setCacheObject(ConstantUntil.SAP_IF_OPEN_JOIN_FUNCTION, "0");
    }


    /**
     * 更新用戶信息到redis
     * @param userName 学号
     * @param userJson 用户信息(json格式)
     */
    public void loginCacheUserToRedis(String userName, String userJson) {
        Map<String, Object> cacheMap = redisCache.getCacheMap(ConstantUntil.SAP_LOGIN);
        cacheMap.put(userName, userJson);
        redisCache.deleteObject(ConstantUntil.SAP_LOGIN);
        redisCache.setCacheMap(ConstantUntil.SAP_LOGIN,cacheMap);
        Map<String, Integer> time = redisCache.getCacheMap(ConstantUntil.SAP_LOGIN_TIME);
        time.put(userName,7);
        redisCache.deleteObject(ConstantUntil.SAP_LOGIN_TIME);
        redisCache.setCacheMap(ConstantUntil.SAP_LOGIN_TIME,time);
    }

    public void deleteCacheUserToRedis(String userName){
        Map<String, Object> cacheMap = redisCache.getCacheMap(ConstantUntil.SAP_LOGIN);
        cacheMap.remove(userName);
        redisCache.deleteObject(ConstantUntil.SAP_LOGIN);
        redisCache.setCacheMap(ConstantUntil.SAP_LOGIN,cacheMap);
        Map<String, Integer> time = redisCache.getCacheMap(ConstantUntil.SAP_LOGIN_TIME);
        time.remove(userName);
        redisCache.deleteObject(ConstantUntil.SAP_LOGIN_TIME);
        redisCache.setCacheMap(ConstantUntil.SAP_LOGIN_TIME,time);
    }
}
